package com.venutech.gongan.api;

import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.framework.security.LoginUser;
import com.venutech.gongan.dto.rpc.common.WorkType;
import com.venutech.gongan.entity.Work;
import com.venutech.gongan.service.*;
import com.venutech.gongan.vo.WorkInfoDto;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;

@Controller
@Api(tags = {"工单系统控制层接口"})
public class WorkController {
    @Resource
    private WorkService workService;

    @Resource
    private WorkSpConfigService workSpConfigService;
    @Resource
    private DictDataService dictDataService;
    @Resource
    private RzLogService rzLogService;


    @Autowired
    private UserService userService;

    @Autowired
    private JkgwService jkgwService;

    @Autowired
    private QdsxjService qdsxjService;

    @RequestMapping("/approveWorkSave")
    @ResponseBody
    public Integer approveWorkSave(WorkInfoDto workDto) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        Work work = workService.getById(workDto.getWorkId());
        if(work.getWk_type() == WorkType.VideoPrivilegeApplication.getValue()) {
            workService.approveVideoPrivilegeWork(workDto.getWorkId(), loginUser.getUserId().intValue());
        } else {
            workService.approveWork(workDto.getWorkId(), loginUser.getUserId().intValue());
        }

        return 0;

    }

    @RequestMapping("/declineWorkSave")
    @ResponseBody
    public Integer declineWorkSave(WorkInfoDto workDto) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        Work work = workService.getById(workDto.getWorkId());

        if(work.getWk_type() == WorkType.VideoPrivilegeApplication.getValue()) {
            workService.declineVideoPrivilegeWork(workDto.getWorkId(), loginUser.getUserId().intValue());
        }

        return 0;
    }

//    @Autowired
//    @Qualifier("eventThreadPool")
//    ExecutorService eventThreadPool;
//
//    @Autowired
//    AuditLogService auditLogService;
//
//    Logger logger = LoggerFactory.getLogger(WorkController.class);
//
//    @RequestMapping("/work_List")
//    @ResponseBody
//    public Map<String, Object> work_List(@RequestParam Integer page, @RequestParam Integer limit,
//                                         @RequestParam(required = false) String begintime,
//                                         @RequestParam(required = false) String endtime,
//                                         @RequestParam(required = false) String poleName,
//                                         @RequestParam(required = false) Integer workStatus,
//                                         @RequestParam(required = false) Integer workType,
//                                         @RequestParam(required = false,defaultValue = "0") Integer type) {
//        Map<String, Object> result = new HashMap<>();
//        User currentUser = oauthContext.getCurrentUser();
//        Page<WorkInfoDto> p = workService.getWorkInfoList(page,limit,begintime,endtime, workType, poleName, workStatus);
//        result.put("code","0");
//        result.put("count",p.getTotal());
//        result.put("data",p.getRecords());
//        if(type==1){
//                try {
//                String message = String.format("工单查询:工单名称:%s", poleName);
//                int logId = rzLogService.addRzLog(currentUser.getUser_id(), Constants.QUERY, message, Constants.LOG_OK, Constants.BACK);
//                }catch (Exception ex){
//                    logger.warn("WorkController.work_List(): 日志记录异常， ex=", ex);
//                }
//        }else{
//            result.put("msg","查询成功");
//        }
//        return result;
//    }
//
//    @RequestMapping("/getPatrolWorkList")
//    @ResponseBody
//    public Map<String, Object> patrolWorkList(@RequestParam Integer page, @RequestParam Integer limit,
//                                              @RequestParam(required = false) String poleName) {
//        Map<String, Object> result = new HashMap<>();
//        Page<WorkInfoDto> p = workService.getPatrolWorkInfoList(page,limit, poleName);
//        result.put("code","0");
//        result.put("msg","成功");
//        result.put("count",p.getTotal());
//        result.put("data",p.getRecords());
//        return result;
//    }
//
//
//    /**
//     * 4小时生成一个工单报告
//     * @return
//     */
//    @RequestMapping("/operationList")
//    public @ResponseBody
//    Map<String,Object> getOperationList(@RequestParam Integer page, @RequestParam Integer limit){
//        Map<String,Object> result =new HashMap<>();
//        int work_device_type=1;
//        Page<Operation> list = workService.selectOperationList(page,limit,work_device_type);
//        result.put("code","0");
//        result.put("msg","成功");
//        result.put("count",list.getTotal());
//        result.put("data",list.getRecords());
//         return  result;
//    }
//
//    @RequestMapping("/getExportExcelWeekList")
//    @ResponseBody
//    public Map<String, Object> getExportExcelWeekList(HttpServletRequest request) {
//
//        logger.info("getExportExcelWeekList 进入 ===============");
//        Map<String, Object> result = new HashMap<String, Object>();
//        User user = oauthContext.getCurrentUser();
//        //查询所有数据集合
//        List<Work> list = workService.getSelByWeek(user.getUser_id());
//        List<Work> newList = new ArrayList<>();
//        for (int i = 0; i <list.size() ; i++) {
//            Work work = list.get(i);
//            if (work.getWk_state()==0){
//                work.setState("未审批");
//            }else if (work.getWk_state()==1){
//                work.setState("已批准");
//            }else if (work.getWk_state()==2){
//                work.setState("已驳回");
//            }
//            newList.add(work);
//        }
//        logger.info("List<Work> ==============="+list);
//        result.put("code","0");
//        result.put("msg","导出成功");
//        result.put("count", list.size());
//        result.put("data", newList);
//
//        return result;
//    }
//
//    @RequestMapping("/getexportExcelMonthList")
//    @ResponseBody
//    public Map<String, Object> getexportExcelMonthList(HttpServletRequest request) {
//
//        logger.info("getExportExcelWeekList 进入 ===============");
//        Map<String, Object> result = new HashMap<String, Object>();
//        User user = oauthContext.getCurrentUser();
//        //查询所有数据集合
//        List<Work> list = workService.getSelByMonth(user.getUser_id());
//        List<Work> newList = new ArrayList<>();
//        for (int i = 0; i <list.size() ; i++) {
//            Work work = list.get(i);
//            if (work.getWk_state()==0){
//                work.setState("未审批");
//            }else if (work.getWk_state()==1){
//                work.setState("已批准");
//            }else if (work.getWk_state()==2){
//                work.setState("已驳回");
//            }
//            newList.add(work);
//        }
//        logger.info("List<Work> ==============="+list);
//        result.put("code","0");
//        result.put("msg","导出成功");
//        result.put("count", list.size());
//        result.put("data", newList);
//
//        return result;
//    }
//
//
//
//    //修改跳转
//    @RequestMapping("/workView")
//    public String workView(Integer wk_id, Model model){
//        User currentUser = oauthContext.getCurrentUser();
//        WorkInfoDto workDto = workService.getWorkInfo(wk_id);
//        //工单类型
//        List<DictData> workTypeList = dictDataService.getSelWorkType();
//        //工单状态
//        List<DictData> workStateList = dictDataService.getSelWorkState();
//
//        model.addAttribute("work",workDto);
//        model.addAttribute("workTypeList",workTypeList);
//        model.addAttribute("workStateList",workStateList);
//        eventThreadPool.execute(() -> {
//            try {
//                String message = String.format("查看摄像机工单:工单Id=%d, 杆件名称=%s", workDto.getWorkId(), workDto.getPoleName());
//                int logId = rzLogService.addRzLog(currentUser.getUser_id(), Constants.VIEW, message, Constants.LOG_OK, Constants.BACK);
//                String opCondition = String.format("wk_id=%d", wk_id);
//                auditLogService.logAudit(currentUser.getLogin_user_name(), currentUser.getNick_name(), currentUser.getEmployee_no(),
//                        currentUser.getId_No(), currentUser.getWork_unit_Name(), currentUser.getWork_unit_Code(), Constants.AUDIT_LOG_OP_TYPE_QUERY,
//                        opCondition, DateTimeUtil.formatDate(new Date(), "yyyyMMddHHmmss"), "1", message, String.valueOf(logId));
//            } catch(Exception ex) {
//                logger.warn("WorkController.workView(): 日志记录异常， ex=", ex);
//            }
//        });
//
//        return "work/work-view";
//    }
//
//    @RequestMapping("/patrolWorkView")
//    public String patrolWorkView(Integer workId, Model model) {
//        User currentUser = oauthContext.getCurrentUser();
//        RzLog rzLog = new RzLog();
//
//        WorkInfoDto workDto = workService.getPatrolWorkInfo(workId);
//        model.addAttribute("patrolWork",workDto);
//
////        //工单类型
////        List<DictData> workTypeList = dictDataService.getSelWorkType();
////        //工单状态
////        List<DictData> workStateList = dictDataService.getSelWorkState();
//
//        eventThreadPool.execute(() -> {
//            try {
//                String message = String.format("查看巡检工单：　工单Id：%d, 杆件名称： %s", workDto.getWorkId(), workDto.getPoleName());
//                int logId = rzLogService.addRzLog(currentUser.getUser_id(), Constants.VIEW, message, Constants.LOG_OK, Constants.BACK);
//
//                String opCondition = String.format("wk_id=%d", workId);
//                auditLogService.logAudit(currentUser.getLogin_user_name(), currentUser.getNick_name(), currentUser.getEmployee_no(),
//                        currentUser.getId_No(), currentUser.getWork_unit_Name(), currentUser.getWork_unit_Code(), Constants.AUDIT_LOG_OP_TYPE_QUERY,
//                        opCondition, DateTimeUtil.formatDate(new Date(), "yyyyMMddHHmmss"), "1", message, String.valueOf(logId));
//            } catch(Exception ex) {
//                logger.warn("WorkController.patrolWorkView(): 日志记录异常， ex=", ex);
//            }
//        });
//        return "patrolWork/patrolWork-view";
//    }




//
//    @GetMapping("/exportWorkExcelDaily/{day}")
//    public void exportWorkExcelDaily(@PathVariable("day")String day, HttpServletResponse response) throws Exception {
//        User currentUser = oauthContext.getCurrentUser();
//        Date startDate = DateTimeUtil.formatDate(day, "yyyy-MM-dd");
//        Date endDate = DateTimeUtil.addDate(startDate,1);
//        String fileName = String.format("前端摄像机工单日报表(%s).xls", DateTimeUtil.dateToString(startDate, "yyyyMMdd"));
//        generateWorkReportExcel(startDate, endDate, fileName, response);
//
//        eventThreadPool.execute(() -> {
//            try {
//                String message = String.format("导出摄像机工单日报表：　%s", day);
//                int logId = rzLogService.addRzLog(currentUser.getUser_id(), Constants.VIEW, message, Constants.LOG_OK, Constants.BACK);
//
//                String opCondition = String.format("startDate=%s and endDate=%s", startDate, endDate);
//                auditLogService.logAudit(currentUser.getLogin_user_name(), currentUser.getNick_name(), currentUser.getEmployee_no(),
//                        currentUser.getId_No(), currentUser.getWork_unit_Name(), currentUser.getWork_unit_Code(), Constants.AUDIT_LOG_OP_TYPE_QUERY,
//                        opCondition, DateTimeUtil.formatDate(new Date(), "yyyyMMddHHmmss"), "1", message, String.valueOf(logId));
//            } catch(Exception ex) {
//                logger.warn("WorkController.exportWorkExcelDaily(): 日志记录异常， ex=", ex);
//            }
//        });
//    }
//
//    @GetMapping("/exportWorkExcelWeekly/{startDay}")
//    public void exportWorkExcelWeekly(@PathVariable("startDay")String startDay, HttpServletResponse response) throws Exception {
//        User currentUser = oauthContext.getCurrentUser();
//        Date startDate =  DateTimeUtil.formatDate(startDay, "yyyy-MM-dd");
//        Date endDate = DateTimeUtil.addDate(startDate,7);
//        String fileName = String.format("前端摄像机工单周报表(%s-%s).xls", DateTimeUtil.dateToString(startDate, "yyyyMMdd"), DateTimeUtil.dateToString(DateTimeUtil.addDate(startDate,6), "yyyyMMdd"));
//        generateWorkReportExcel(startDate, endDate, fileName, response);
//
//        eventThreadPool.execute(() -> {
//            try {
//                String message = String.format("导出摄像机工单周报表：　%s-%s", startDay, DateTimeUtil.dateToString(DateTimeUtil.addDate(startDate,6), "yyyyMMdd"));
//                int logId = rzLogService.addRzLog(currentUser.getUser_id(), Constants.VIEW, message, Constants.LOG_OK, Constants.BACK);
//
//                String opCondition = String.format("startDate=%s and endDate=%s", startDate, endDate);
//                auditLogService.logAudit(currentUser.getLogin_user_name(), currentUser.getNick_name(), currentUser.getEmployee_no(),
//                        currentUser.getId_No(), currentUser.getWork_unit_Name(), currentUser.getWork_unit_Code(), Constants.AUDIT_LOG_OP_TYPE_QUERY,
//                        opCondition, DateTimeUtil.formatDate(new Date(), "yyyyMMddHHmmss"), "1", message, String.valueOf(logId));
//            } catch(Exception ex) {
//                logger.warn("WorkController.exportWorkExcelWeekly(): 日志记录异常， ex=", ex);
//            }
//        });
//    }
//
//    @GetMapping("/exportWorkExcelMonthly/{startMonth}")
//    public void exportWorkExcelMonthly(@PathVariable("startMonth") String startMonth, HttpServletResponse response) throws Exception {
//        User currentUser = oauthContext.getCurrentUser();
//        Date startDate = DateTimeUtil.formatDate(String.format("%s-01", startMonth), "yyyy-MM-dd");
//        Calendar calendar = Calendar.getInstance();
//        calendar.setTime(startDate);
//        calendar.add(Calendar.MONTH, 1);
//        Date endDate = calendar.getTime();
//        String fileName = String.format("前端摄像机工单月报表(%s).xls", startMonth);
//        generateWorkReportExcel(startDate, endDate, fileName, response);
//
//        eventThreadPool.execute(() -> {
//            try {
//                String message = String.format("导出摄像机工单月报表：　%s", startMonth);
//                int logId = rzLogService.addRzLog(currentUser.getUser_id(), Constants.VIEW, message, Constants.LOG_OK, Constants.BACK);
//
//                String opCondition = String.format("startDate=%s and endDate=%s", startDate, endDate);
//                auditLogService.logAudit(currentUser.getLogin_user_name(), currentUser.getNick_name(), currentUser.getEmployee_no(),
//                        currentUser.getId_No(), currentUser.getWork_unit_Name(), currentUser.getWork_unit_Code(), Constants.AUDIT_LOG_OP_TYPE_QUERY,
//                        opCondition, DateTimeUtil.formatDate(new Date(), "yyyyMMddHHmmss"), "1", message, String.valueOf(logId));
//            } catch(Exception ex) {
//                logger.warn("WorkController.exportWorkExcelMonthly(): 日志记录异常， ex=", ex);
//            }
//        });
//    }
//
//    @GetMapping("/exportWorkExcelSpan/{startDate}/{endDate}")
//    public void exportWorkExcelSpan(@PathVariable("startDate") String startDate, @PathVariable("endDate") String endDate, HttpServletResponse response) throws Exception {
//        User currentUser = oauthContext.getCurrentUser();
//        Date startDay =  DateTimeUtil.formatDate(startDate, "yyyy-MM-dd");
//        Date endDay = DateTimeUtil.addDate(DateTimeUtil.formatDate(endDate, "yyyy-MM-dd"),1);
//        String fileName = String.format("前端摄像机工单报表(%s-%s).xls", startDate, endDate);
//        generateWorkReportExcel(startDay, endDay, fileName, response);
//        eventThreadPool.execute(() -> {
//            try {
//                String message = String.format("导出摄像机工单报表：　%s-%s", startDate, endDate);
//                int logId = rzLogService.addRzLog(currentUser.getUser_id(), Constants.VIEW, message, Constants.LOG_OK, Constants.BACK);
//
//                String opCondition = String.format("startDate=%s and endDate=%s", startDate, endDate);
//                auditLogService.logAudit(currentUser.getLogin_user_name(), currentUser.getNick_name(), currentUser.getEmployee_no(),
//                        currentUser.getId_No(), currentUser.getWork_unit_Name(), currentUser.getWork_unit_Code(), Constants.AUDIT_LOG_OP_TYPE_QUERY,
//                        opCondition, DateTimeUtil.formatDate(new Date(), "yyyyMMddHHmmss"), "1", message, String.valueOf(logId));
//            } catch(Exception ex) {
//                logger.warn("WorkController.exportWorkExcelSpan(): 日志记录异常， ex=", ex);
//            }
//        });
//    }
//
//
//    @GetMapping("/exportPatrolWorkExcelDaily/{day}")
//    public void exportPatrolWorkExcelDaily(@PathVariable("day")String day, HttpServletResponse response) throws Exception {
//        User currentUser = oauthContext.getCurrentUser();
//        Date startDate = DateTimeUtil.formatDate(day, "yyyy-MM-dd");
//        Date endDate = DateTimeUtil.addDate(startDate,1);
//        String fileName = String.format("巡检工单日报表(%s).xls", DateTimeUtil.dateToString(startDate, "yyyyMMdd"));
//        generatePatrolWorkReportExcel(startDate, endDate, fileName, response);
//        eventThreadPool.execute(() -> {
//            try {
//                String message = String.format("导出巡检工单日报表：　%s", day);
//                int logId = rzLogService.addRzLog(currentUser.getUser_id(), Constants.VIEW, message, Constants.LOG_OK, Constants.BACK);
//                String opCondition = String.format("startDate=%s and endDate=%s", startDate, endDate);
//                auditLogService.logAudit(currentUser.getLogin_user_name(), currentUser.getNick_name(), currentUser.getEmployee_no(),
//                        currentUser.getId_No(), currentUser.getWork_unit_Name(), currentUser.getWork_unit_Code(), Constants.AUDIT_LOG_OP_TYPE_QUERY,
//                        opCondition, DateTimeUtil.formatDate(new Date(), "yyyyMMddHHmmss"), "1", message, String.valueOf(logId));
//            } catch(Exception ex) {
//                logger.warn("WorkController.exportPatrolWorkExcelDaily(): 日志记录异常， ex=", ex);
//            }
//        });
//    }
//
//    @GetMapping("/exportPatrolWorkExcelWeekly/{startDay}")
//    public void exportPatrolWorkExcelWeekly(@PathVariable("startDay")String startDay, HttpServletResponse response) throws Exception {
//        User currentUser = oauthContext.getCurrentUser();
//        Date startDate =  DateTimeUtil.formatDate(startDay, "yyyy-MM-dd");
//        Date endDate = DateTimeUtil.addDate(startDate,7);
//        String fileName = String.format("巡检工单周报表(%s-%s).xls", DateTimeUtil.dateToString(startDate, "yyyyMMdd"), DateTimeUtil.dateToString(DateTimeUtil.addDate(startDate,6), "yyyyMMdd"));
//        generatePatrolWorkReportExcel(startDate, endDate, fileName, response);
//        eventThreadPool.execute(() -> {
//            try {
//                String message = String.format("导出巡检工单周报表：　%s-%s", startDay, DateTimeUtil.dateToString(DateTimeUtil.addDate(startDate,6), "yyyyMMdd"));
//                int logId = rzLogService.addRzLog(currentUser.getUser_id(), Constants.VIEW, message, Constants.LOG_OK, Constants.BACK);
//
//                String opCondition = String.format("startDate=%s and endDate=%s", startDate, endDate);
//                auditLogService.logAudit(currentUser.getLogin_user_name(), currentUser.getNick_name(), currentUser.getEmployee_no(),
//                        currentUser.getId_No(), currentUser.getWork_unit_Name(), currentUser.getWork_unit_Code(), Constants.AUDIT_LOG_OP_TYPE_QUERY,
//                        opCondition, DateTimeUtil.formatDate(new Date(), "yyyyMMddHHmmss"), "1", message, String.valueOf(logId));
//            } catch(Exception ex) {
//                logger.warn("WorkController.exportPatrolWorkExcelWeekly(): 日志记录异常， ex=", ex);
//            }
//        });
//    }
//
//
//    @GetMapping("/exportPatrolWorkExcelMonthly/{startMonth}")
//    public void exportPatrolWorkExcelMonthly(@PathVariable("startMonth") String startMonth, HttpServletResponse response) throws Exception {
//        User currentUser = oauthContext.getCurrentUser();
//        Date startDate = DateTimeUtil.formatDate(String.format("%s-01", startMonth), "yyyy-MM-dd");
//        Calendar calendar = Calendar.getInstance();
//        calendar.setTime(startDate);
//        calendar.add(Calendar.MONTH, 1);
//        Date endDate = calendar.getTime();
//        String fileName = String.format("巡检工单月报表(%s).xls", startMonth);
//        generatePatrolWorkReportExcel(startDate, endDate, fileName, response);
//        eventThreadPool.execute(() -> {
//            try {
//                String message = String.format("导出巡检工单月报表：　%s", startMonth);
//                int logId = rzLogService.addRzLog(currentUser.getUser_id(), Constants.VIEW, message, Constants.LOG_OK, Constants.BACK);
//                String opCondition = String.format("startDate=%s and endDate=%s", startDate, endDate);
//                auditLogService.logAudit(currentUser.getLogin_user_name(), currentUser.getNick_name(), currentUser.getEmployee_no(),
//                        currentUser.getId_No(), currentUser.getWork_unit_Name(), currentUser.getWork_unit_Code(), Constants.AUDIT_LOG_OP_TYPE_QUERY,
//                        opCondition, DateTimeUtil.formatDate(new Date(), "yyyyMMddHHmmss"), "1", message, String.valueOf(logId));
//
//            } catch(Exception ex) {
//                logger.warn("WorkController.exportWorkExcelMonthly(): 日志记录异常， ex=", ex);
//            }
//        });
//    }
//
//    @GetMapping("/exportPatrolWorkExcelSpan/{startDate}/{endDate}")
//    public void exportPatrolWorkExcelSpan(@PathVariable("startDate") String startDate, @PathVariable("endDate") String endDate, HttpServletResponse response) throws Exception {
//        User currentUser = oauthContext.getCurrentUser();
//        Date startDay =  DateTimeUtil.formatDate(startDate, "yyyy-MM-dd");
//        Date endDay = DateTimeUtil.addDate(DateTimeUtil.formatDate(endDate, "yyyy-MM-dd"),1);
//        String fileName = String.format("巡检工单报表(%s-%s).xls", startDate, endDate);
//        generatePatrolWorkReportExcel(startDay, endDay, fileName, response);
//        eventThreadPool.execute(() -> {
//            try {
//                String message = String.format("导出巡检工单报表：　%s-%s", startDate, endDate);
//                int logId = rzLogService.addRzLog(currentUser.getUser_id(), Constants.VIEW, message, Constants.LOG_OK, Constants.BACK);
//                String opCondition = String.format("startDate=%s and endDate=%s", startDate, endDate);
//                auditLogService.logAudit(currentUser.getLogin_user_name(), currentUser.getNick_name(), currentUser.getEmployee_no(),
//                        currentUser.getId_No(), currentUser.getWork_unit_Name(), currentUser.getWork_unit_Code(), Constants.AUDIT_LOG_OP_TYPE_QUERY,
//                        opCondition, DateTimeUtil.formatDate(new Date(), "yyyyMMddHHmmss"), "1", message, String.valueOf(logId));
//            } catch(Exception ex) {
//                logger.warn("WorkController.exportWorkExcelSpan(): 日志记录异常， ex=", ex);
//            }
//        });
//    }
//
//
//    private void generateWorkReportExcel(Date startDate, Date endDate, String fileName, HttpServletResponse response)  throws Exception  {
//        HashMap<String, List<List<String>>> sheetMap = new HashMap<>();
//        List<Work> reportWorks = workService.getByTypeAndDateRange(Constants.WORK_TYPE_REPORT, startDate, endDate);
//        List<List<String>> reportRows = assembleWorkReportExcelData(reportWorks, Constants.WORK_TYPE_REPORT);
//        sheetMap.put("前端摄像机工单上报", reportRows);
//
////        List<Work> videoApplicationWorks = workService.getByTypeAndDateRange(Constants.WORK_TYPE_VIDEO_PRIVILEGE_APPLICATION, startDate, endDate);
////        List<List<String>> videoApplicationRows = assembleExcelData(reportWorks, Constants.WORK_TYPE_VIDEO_PRIVILEGE_APPLICATION);
////        sheetMap.put("视频权限申请", videoApplicationRows);
//
//        ExcelUtils.exportMultiSheetExcel(sheetMap, fileName, response);
//    }
//
//    private void generatePatrolWorkReportExcel(Date startDate, Date endDate, String fileName, HttpServletResponse response)  throws Exception  {
//        HashMap<String, List<List<String>>> sheetMap = new HashMap<>();
//        List<Work> patrolWorks = workService.getByTypeAndDateRange(Constants.WORK_TYPE_PATROL, startDate, endDate);
//        List<List<String>> patrolRows = assemblePatrolWorkReportExcelData(patrolWorks, Constants.WORK_TYPE_PATROL);
//        sheetMap.put("巡检打卡", patrolRows);
//
//        List<List<String>> patrolPercentRows = caculatePatrolPercent(patrolWorks, startDate, endDate);
//        sheetMap.put("打卡率统计", patrolPercentRows);
//
//        ExcelUtils.exportMultiSheetExcel(sheetMap, fileName, response);
//    }
//
//    private List<List<String>> assembleWorkReportExcelData(List<Work> works, int workType) {
//        List<List<String>> rows = new ArrayList<>();
//        if(CollectionUtils.isEmpty(works)) {
//            return rows;
//        }
//
//        List<String> meta = new ArrayList<>();
//        meta.add("工单类型");
//        meta.add("申请人");
//        meta.add("工单内容");
//        meta.add("杆位名称");
//        meta.add("设备名称");
//        meta.add("上报时间");
//        meta.add("工单状态");
//        meta.add("审批人");
//        rows.add(meta);
//
//        String workTypeName = "";
//        if(workType == Constants.WORK_TYPE_REPORT) {
//            workTypeName = "事件上报";
//        } else if(workType == Constants.WORK_TYPE_VIDEO_PRIVILEGE_APPLICATION) {
//            workTypeName = "视频权限申请";
//        } else if(workType == Constants.WORK_TYPE_PATROL) {
//            workTypeName = "巡检上报";
//        }
//
//        for(Work work: works) {
//            List<String> row = new ArrayList<>();
//            row.add(workTypeName);
//            if(Objects.nonNull(work.getWk_sq_user_id()) && work.getWk_sq_user_id() > 0 ) {
//                User user = userService.getById(work.getWk_sq_user_id());
//                if(Objects.nonNull(user)) {
//                    String applier = user.getNick_name();
//                    row.add(applier);
//                }
//            }
//            row.add(work.getWk_content());
//            if(Objects.nonNull(work.getWk_gw_id()) && work.getWk_gw_id() > 0) {
//                Jkgw jkgw = jkgwService.getById(work.getWk_gw_id());
//                if(Objects.nonNull(jkgw)) {
//                    row.add(jkgw.getGw_name());
//                }
//            }
//            if(Objects.nonNull(work.getWk_sb_id()) && work.getWk_sb_id() > 0)  {
//                Qdsxj equip = qdsxjService.getById(work.getWk_sb_id());
//                if(Objects.nonNull(equip)) {
//                    row.add(equip.getSb_name());
//                }
//            }
//            if(Objects.nonNull(work.getWk_sq_time())) {
//                row.add(DateTimeUtil.formatDate(work.getWk_sq_time(), "yyyy-MM-dd HH:mm:ss"));
//            }
//            String workStateName = "";
//            if(work.getWk_state() == 0) {
//                workStateName = "未审批";
//            } else if(work.getWk_state() == 1) {
//                workStateName = "已批准";
//            } else if(work.getWk_state() == 2) {
//                workStateName = "未批准";
//            }
//            row.add(workTypeName);
//            if(Objects.nonNull(work.getWk_sp_user_id()) && work.getWk_sp_user_id() > 0 ) {
//                User user = userService.getById(work.getWk_sp_user_id());
//                if(Objects.nonNull(user)) {
//                    String approver = user.getNick_name();
//                    row.add(approver);
//                }
//            }
//            rows.add(row);
//        }
//
//        return rows;
//    }
//
//    private List<List<String>> assemblePatrolWorkReportExcelData(List<Work> works, int workType) {
//        List<List<String>> rows = new ArrayList<>();
//        if(CollectionUtils.isEmpty(works)) {
//            return rows;
//        }
//
//        List<String> meta = new ArrayList<>();
//        meta.add("工单类型");
//        meta.add("上报人");
//        meta.add("工单内容");
//        meta.add("杆位ID");
//        meta.add("杆位名称");
//        meta.add("上报时间");
//        rows.add(meta);
//
//        String workTypeName = "巡检上报";
//
//        for(Work work: works) {
//            List<String> row = new ArrayList<>();
//            row.add(workTypeName);
//            if(Objects.nonNull(work.getWk_sq_user_id()) && work.getWk_sq_user_id() > 0 ) {
//                User user = userService.getById(work.getWk_sq_user_id());
//                if(Objects.nonNull(user)) {
//                    String applier = user.getNick_name();
//                    row.add(applier);
//                }
//            }
//            row.add("巡检打卡");
//            if(Objects.nonNull(work.getWk_gw_id()) && work.getWk_gw_id() > 0) {
//                Jkgw jkgw = jkgwService.getById(work.getWk_gw_id());
//                if(Objects.nonNull(jkgw)) {
//                    row.add(String.valueOf(jkgw.getGw_id()));
//                    row.add(jkgw.getGw_name());
//                }
//            }
//            if(Objects.nonNull(work.getWk_sq_time())) {
//                row.add(DateTimeUtil.formatDate(work.getWk_sq_time(), "yyyy-MM-dd HH:mm:ss"));
//            }
//
//            rows.add(row);
//        }
//
//        return rows;
//    }
//
//
//    /**
//     *　计算各个杆件的扎打卡率
//     * @param patrolWorks
//     * @param startDate
//     * @param endDate
//     * @return
//     */
//    private List<List<String>> caculatePatrolPercent(List<Work> patrolWorks, Date startDate, Date endDate) {
//
//        List<List<String>> rows = new ArrayList<>();
//        List<String> meta = new ArrayList<>();
//        meta.add("杆件ID");
//        meta.add("杆件名称");
//        meta.add("打卡率");
//        rows.add(meta);
//        if(CollectionUtils.isEmpty(patrolWorks)) {
//            return rows;
//        }
//
//        Map<Integer, List<Work>> groupMap = patrolWorks.stream().collect(Collectors.groupingBy(pw -> pw.getWk_gw_id()));
//        for(Map.Entry<Integer, List<Work>> entry : groupMap.entrySet()) {
//            int poleId = entry.getKey();
//            String poleName = jkgwService.getById(poleId).getGw_name();
//            String patrolPercent = caculatePatrolPercentForPole(patrolWorks, startDate, endDate);
//
//            List<String> row = new ArrayList<>();
//            row.add(String.valueOf(poleId));
//            row.add(poleName);
//            row.add(patrolPercent);
//            rows.add(row);
//        }
//        return rows;
//    }
//
//
//    /**
//     * 计算杆件打卡率，　分子：当期时间段内打卡天数，　分母：　时间段内天数
//     */
//    private String caculatePatrolPercentForPole(List<Work> patrolWorksForPole, Date startDate, Date endDate) {
//        int patrolDays = 0;
//        if(!CollectionUtils.isEmpty(patrolWorksForPole)) {
//            Map<Date, List<Work>> groupMap = patrolWorksForPole.stream().collect(Collectors.groupingBy(pt -> DateTimeUtil.getDayStart(pt.getWk_sq_time())));
//            patrolDays = groupMap.size();
//        }
//        int allDays = getSpanDays(startDate, endDate);
//
//        if(patrolDays == 0) {
//            return "0.00%";
//        }
//        if(patrolDays == allDays) {
//            return "100.00";
//        }
//
//
//        DecimalFormat df =new DecimalFormat();
//        df.setMaximumFractionDigits(2);
//        df.setMinimumFractionDigits(2);
//
//        String percent = df.format(patrolDays *100.00 / allDays) +"%";
//        return percent;
//
//    }
//
//    private int getSpanDays(Date date1,Date date2) {
//        int days = (int) ((date2.getTime() - date1.getTime()) / (1000*3600*24));
//        return days;
//    }
}
